<?php Workerman\Protocols\Http::sessionStart(); $G_MODEL_NAME = basename(__FILE__,'.js.php'); $G_MODEL_URL = $_SESSION["MES_WEB_URL"].'/'. $G_MODEL_NAME; ?>

<?php @$G_MODEL_GET_POSTER_ID = $_GET['poster_id'];?>
<?php $access_token = $_SESSION["ACCESS_TOKEN"];?>

var _poster_id = '<?php echo $G_MODEL_GET_POSTER_ID;?>';



var object_selected = false; //添加画布标注按钮拖动

var textObj = "";//全部按钮数据

var csv_poster_id , csv_page , csv_department_id; //导出按钮参数

var identity = localStorage.getItem("identityPC")




//返回订单界面
function openOrderConfig(poster_id) {

    $("#mod_body").html("");
    $.get("./modules/poster_information/mod_poster_information_management.php?poster_id="+poster_id,function(result){
        $("#mod_body").html(result);
        $.getScript("./modules/poster_information/mod_poster_information_management.js.php?poster_id="+poster_id,
            function() {
                //完成 modules js load
                //newFun('"Checking new script"'); //这个函数是在new.js里面的，当点击click后运行这个函数
            });
    });
};

$("[name='btn_mod_poster_information_management_details_return']").click(function(){
    window.setTimeout("openOrderConfig("+ _poster_id +")", 300);
})


for (var selector in chosen_config) {
    $(selector).chosen(chosen_config[selector]);
    $(".chosen-container ").css("width",$(selector).width());
}

$('.input-daterange').datepicker({
    keyboardNavigation: false,
    todayBtn: 'linked',
    todayHighlight:true,
    forceParse: false,
    calendarWeeks: true,
    autoclose: true,
    format: 'yyyy-mm-dd',
    language: 'zh-CN'
});

PICTURE_LIST_DATA = [];

// 初始化画布
var canvas=new fabric.Canvas('myCanvas_oo');
var panning = false;
fabric.textureSize = 4096;
canvas.preserveObjectStacking = true;


canvas.setWidth( $("#upper-canvas").width() );
canvas.setHeight( document.body.clientHeight-265 );
canvas.calcOffset();

$("#upper-canvas").on('resize',function(){
    setTimeout(function(){
        console.log("aa", $("#upper-canvas").width()-10);
        //$("#myCanvas_oo").attr("width", $("#upper-canvas").width());
        //$("#myCanvas_oo").attr("height", document.body.clientHeight-265);
        canvas.setWidth( $("#upper-canvas").width() );
        canvas.setHeight( document.body.clientHeight-265 );
        canvas.calcOffset();

        canvas.renderAll();
    },500);
});

// ================== 转移到画布对应的left top ========================
function set_center(left, top){
    let centerX = canvas.width/2;
    let centerY = canvas.height/2;
    let delta = new fabric.Point(left - centerX, top - centerY);
    canvas.absolutePan(delta);
    //canvas.requestRenderAll();
}

// ================== 将Json导入到canvas中 ============================
function set_texts(json_data){
    for(let i in json_data){
        add_text(t=json_data[i].text, highlight=false, json=json_data[i] , lockingIndex=i)
    }
}

function get_texts(){
    let os = canvas.getObjects();

    let rtval = [];
    let rtvalInfo = [];
    let rtvalIs_confirm = [];
    let rtvalTagging = [];
    let revalLocking = [];
    let revalDepartment_name = [];
    for(i in os){
        if(os[i].type=="i-text" || os[i].type=="text"){
            rtval.push(os[i].toJSON());
            rtvalInfo.push({info:os[i].info});
            rtvalIs_confirm.push({is_confirm:os[i].is_confirm});
            rtvalTagging.push({tagging:os[i].tagging});
            revalLocking.push({locking:os[i].locking});
            revalDepartment_name.push({department_name:os[i].department_name});
        }
    }

    for (let i = 0; i < rtval.length;i++){
         Object.assign(rtval[i] , rtvalInfo[i] , rtvalIs_confirm[i] , rtvalTagging[i] , revalLocking[i] , revalDepartment_name[i]);
    }


    return rtval;
}

function text_count(){
    $("#list-text-badge").text(get_texts().length);
}





// ================== 添加标注的函数 ==================================
// 当参数为json的时候，优先处理json
let dataInfo =  {
        "sku": "",
        "unit": "",
        "price": "",
        "name": "",
        "desc": "",
        "page": "",
        "idx": "",
        "s_price": "",
        "limit": "",
        "area_time": "",
        "mark": "",
        "origin": "",
        "flag": "",
        "department_name": ""
};

function add_text(t=' 标注 ' , highlight=false, json=null , lockingIndex){
    let color = '#000';
    if(highlight)
        color = '#F00';
    let p = canvas.getCenter();
    let vp = canvas.getVpCenter();
    let left = vp.x-20;
    let is_confirm = false;
    let info = dataInfo;
    let tagging = "";
    let locking = [false , false , false , false];
    let department_name = "";


    let top = vp.y-20;
    if(json!=null){


        if(typeof(json['left'])!='undefined' && typeof(json['top'])!='undefined'){
            left = json['left'];
            top  = json['top'];
        }
        if(typeof(json['fill'])!='undefined'){
            color = json['fill'];
        }
        if(typeof(json['text'])!='undefined'){
            t = json['text'];
        }

        if (typeof(json['info']) != 'undefined'){
            info = json['info'];
        }
        if (typeof(json['is_confirm']) != 'undefined'){
            is_confirm = json['is_confirm'];
        }
        if (typeof(json['tagging']) != 'undefined'){
            tagging = json['tagging'];
        }
        if (typeof(json['locking']) != 'undefined'){
            locking = json['locking'];
        }

        if (JSON.stringify(info) == JSON.stringify(dataInfo)){
            department_name = get_texts()[0].info.department_name;
        }else{
            department_name = info.department_name;
        }




    }

    let btnEl = document.getElementsByClassName("locking-btn");

    let text = null;
    let selected = "";
    if (locking[identity]){
        btnEl[lockingIndex].innerHTML = "取消修改";
        text  = new fabric.Text(t,{
            left:left,
            top:top,
            fill: "#2d8cf0",
            fontFamily: '1',
            backgroundColor: 'rgba(255,255,255,0.8)',
            fontSize:35,
            padding:10,
            borderScaleFactor:3,
            fontWeight: 'bold',
            opacity:1
        });
        selected = false;
    } else {
        btnEl[lockingIndex].innerHTML = "确认修改";
        text  = new fabric.IText(t,{
            left:left,
            top:top,
            fill: "#F00",
            fontFamily: '1',
            backgroundColor: 'rgba(255,255,255,0.8)',
            fontSize:35,
            padding:10,
            borderScaleFactor:3,
            fontWeight: 'bold',
            opacity:1
        });
        selected = true;
    }




    text.info = info;
    text.tagging = tagging;
    text.is_confirm = is_confirm;
    text.locking = locking;
    text.department_name = department_name;



    //添加画布标注按钮拖动start
    text.on('mousedown', function(e) {
        object_selected = selected;
        panning = true
        text.selection = false;
    });





    text.on('mouseup', function() {
        object_selected = false;
        text.selection = true;
        panning = false;
    });

    text.on('editing:exited', function() {

        let textArr = get_texts().map(item=>{return item.text;} );
        let newTextArr = [];
        let newTextArr2 = [];
        textArr.map(item=>{
            if (newTextArr.indexOf(item) === -1){
            newTextArr.push(item)
        }else {
            newTextArr2.push(item)
        }
        });

        if (newTextArr2.length > 0){
            swal("提示","标记文本有重复 ， 请修改···","error");
            this.text = t;
            return
        }

        //添加左右空格
        let s = this.text;
        s = s.replace(/(^\s*)|(\s*$)/g, "");
        s = " " + s + " ";
        this.text = s;
    });


    text.lockScalingX = true;
    text.lockScalingY = true;
    text.lockRotation = true;

    canvas.add(text);
    canvas.renderAll();
    text_count();








    //添加画布标注按钮拖动end

    //text.set('selectable',false);
    //text.selection = false;
    //text.lockScalingX = true;
    //text.lockScalingY = true;
    //text.lockRotation = true;
    //canvas.add(text);
    //canvas.visible = false;



}


// ============= 定义画布事件 ====================
//鼠标滚轮监听
canvas.on("mouse:wheel", function(e) {
    var zoom = (event.deltaY > 0 ? -0.1 : 0.1) + canvas.getZoom();
    zoom = Math.max(0.2, zoom); //最小为原来的1/10
    zoom = Math.min(2, zoom); //最大是原来的3倍
    var zoomPoint = new fabric.Point(event.pageX, event.pageY);
    canvas.zoomToPoint(zoomPoint, zoom);
});

//鼠标按下
canvas.on('mouse:down', function (e) {


    if(object_selected) return

    //按住alt键才可拖动画布
    //if(e.e.altKey) {
    panning = true;
    canvas.selection = false;
    //}
});

//鼠标抬起
canvas.on('mouse:up', function (e) {


    if(object_selected) return

    panning = false;
    canvas.selection = true;
});

//鼠标移动
canvas.on('mouse:move', function (e) {

    if(object_selected) return

    if (panning && e && e.e) {
        var delta = new fabric.Point(e.e.movementX, e.e.movementY);
        canvas.relativePan(delta);
    }
});

// 获取海报校稿次数
var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_poster_number","poster_id":_poster_id},access_token:"<?php echo $access_token?>"};

//校稿id
var proofread_id = "";
ajax_request(param,function(result){
    try{
        var result = JSON.parse(result);
        result = result["rtval"];
        proofread_id =  result.data[0].poster_contents_id;
        var obj = result;
    }catch(e){
        swal(e);
        return;
    }

    var first_picture_path = "";
    var first_poster_contents = "";

    $("#poster_num_tab").empty();
    $("#picture_tab").empty();
    $('[name="mod_poster_picture_department"]').empty();

    var poster_number = obj["data"];
    var poster_num_tab_str = "";
    var first_poster_contents_id = "";
    for(let key  in poster_number){
        var poster_num_tab_active = "";

        var num = poster_number[key]["number"];
        var poster_contents_id = poster_number[key]["poster_contents_id"];
        if(num == "1"){
            poster_num_tab_active = "active";
            first_poster_contents_id = poster_contents_id;
        }
        poster_num_tab_str += '<li class="'+poster_num_tab_active+'"><a class="poster_tab_a"  poster-contents-id="'+poster_contents_id+'"  poster-key="'+num+'" data-toggle="tab" href="#tab-'+num+'" aria-expanded="true">第'+num+'次校稿1</a></li>';

    }

    $("#poster_num_tab").html(poster_num_tab_str);

    get_page_number(first_poster_contents_id,true);


});



// 获取页数
var get_page_number = function(poster_contents_id,is_first=false){

    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_page_number_by_poster","poster_contents_id":poster_contents_id},access_token:"<?php echo $access_token?>"};
    ajax_request(param,function(result){
        var result = JSON.parse(result);
        result = result["rtval"];
        $('[name="mod_poster_picture_page"]').empty();
        var first_page = "";
        for(v in result["page_number"]){
            var page = result["page_number"][v];
            if(v == 0){
                first_page = page;
            }
            $('[name="mod_poster_picture_page"]').append('<option value="' + page + '">第' + page + '页</option>');
        }
        $('[name="mod_poster_picture_page"]').trigger("chosen:updated");

        // 如果是初次加载，则默认加载第一项
        if(is_first == true){
            get_department_id(poster_contents_id,first_page,true);
        }
    })
}

//获取部门信息
var get_department_id = function(poster_contents_id,page,is_first=false){

    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_department_id_by_poster_page","poster_contents_id":poster_contents_id,page:page},access_token:"<?php echo $access_token?>"};
    ajax_request(param,function(result){
        var result = JSON.parse(result);
        result = result["rtval"]["department_arr"];
        $('[name="mod_poster_picture_department"]').empty();
        var first_department_id = "";
        for(v in result){
            var department_id = result[v]["department_id"];
            var name = result[v]["name"];
            if(v == 0){
                first_department_id = department_id;
            }
            $('[name="mod_poster_picture_department"]').append('<option value="' + department_id + '">' + name + '</option>');
        }
        $('[name="mod_poster_picture_department"]').append('<option value="0">部门合并图</option>');
        $('[name="mod_poster_picture_department"]').trigger("chosen:updated");




        // 如果是初次加载，则默认加载第一项
        if(is_first == true){
            get_picture_list(poster_contents_id,page,first_department_id ,false ,department_id );
        }else {
            get_picture_list(poster_contents_id,page,first_department_id , true , department_id);
        }
    })
}


var get_page_btn = function (poster_management_id ,page) {

    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_poster_button","poster_management_id":poster_management_id , "page":page ,"department_id":0},access_token:"<?php echo $access_token?>"};
        ajax_request(param,function(result){
            $("#all-btn-details tbody").html("")
            if(JSON.parse(result)["rtval"].length <= 0) return;
            let str = "";
            JSON.parse(result)["rtval"].button_json.map((item , index)=>{
                str += `<tr><td class="text-center">${index}</td><td>${item.text}</td> <td>
                      <div class="btn-group btn-select" index="${index}" >
                                <button  class="btn btn-default btn-xs dropdown-toggle"  style="position: relative; z-index: 999999;">查看<span class="caret" style="margin-left:3px;"></span>
                                </button>
                               ${createBtnDetails(item.info , index)}
                            </div>
                       </td> </tr>`;
            })
      $("#all-btn-details tbody").html(str)

            $(".btn-select").hover(function () {
               $(".btn-item-details").get($(this).attr("index")).style.display = "block";
            } , function () {
                $(".btn-item-details").get($(this).attr("index")).style.display = "none";
            })
    })
}

function createBtnDetails(data , index){
    let str = ""


    let text = {
        "sku": "sku",
        "unit": "unit",
        "price": "price",
        "name": "name",
        "desc": "desc",
        "page": "page",
        "idx": "idx",
        "s_price": "s_price",
        "limit": "limit",
        "area_time": "area_time",
        "mark": "mark",
        "origin": "origin",
        "flag": "flag",
        "department_name": "department_name"
    }


    for(key in data){
       str += `
            <li class="flex" style="margin:10px 0;justify-content: space-around;">
                <div style="width:20%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="${text[key]}">${text[key]}</div>:
                <textarea id="ccomment" name="comment" class="form-control" style="height: 30px;" required="" aria-required="true" disabled> ${data[key]}</textarea>
            </li>
       `;

    }


   let strAll = `<ul class="btn-item-details"  style="display: none; width: 300px;left: -200%;padding:0 10px;position: absolute;top: 22px;background: #ffffff;z-index: 9999999;border: 1px solid #cccccc;">${str}</ul>`;
    return strAll;

}







//导入按钮列表
let importBtnList = [];
//获取海报 按钮 信息

var get_poster_button = function(poster_management_id , page , contentData ,boolIndex , department_id , mergeImgForm){
    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_poster_button","poster_management_id":poster_management_id , "page":page ,"department_id":department_id},access_token:"<?php echo $access_token?>"};
    ajax_request(param,function(result){
        var result = JSON.parse(result);
        result = result["rtval"].button_json;
        PICTURE_LIST_DATA = JSON.stringify(result);
        importBtnList =  result;

        textObj = contentData;
        if (!textObj.contents){
            textObj.contents = JSON.stringify(importBtnList);
        }

        if (boolIndex){
            change_picture_path(textObj , true , mergeImgForm);
        }else{
            change_picture_path(textObj , false , mergeImgForm);

        }

    })

    get_page_btn(poster_management_id , page);


}




var picture_department_id = "";
//获取海报信息
var get_picture_list = function(poster_contents_id,page,department_id , boolIndex , mergeImgForm){
    csv_poster_id = poster_contents_id;
    csv_page = page;
    csv_department_id = department_id;

    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_picture_list_by_poster_page_department","poster_contents_id":poster_contents_id,page:page,department_id:department_id},access_token:"<?php echo $access_token?>"};
    ajax_request(param,function(result){

        var result = JSON.parse(result);
        result = result["rtval"];
        PICTURE_LIST_DATA = result;



        var picture_tab_str = "";
        var first_picture_path = "";
        var first_contents = "";
        var first_user_name = "";
        var first_picture_department_id = "";
        var first_contents_confirm = "";
        var first_deputy_director_name = "";
        var first_chief_inspector_name = "";
        result.forEach(function(val,index){

            var picture_tab_active = "";
            if(index == 0){
                picture_tab_active = "active";
                first_picture_path = val["picture_path"];
                first_contents = val["contents"];
                first_user_name = val["user_name"];
                first_picture_department_id = val["picture_department_id"];
                first_contents_confirm = val["contents_confirm"];

                picture_department_id = val["picture_department_id"];

                first_deputy_director_name = val["deputy_director_name"];
                first_chief_inspector_name = val["chief_inspector_name"];
            }
            var area_text = area_name(val["area"]);
            picture_tab_str += '<li class="'+picture_tab_active+'"><a data-toggle="tab" picture-key="'+index+'" picture-path="'+val["picture_path"]+'" picture_department_id="'+val["picture_department_id"]+'" class="picture_tab_a"><img alt="image" class="img-circle" style="width: 90px;height: 90px;border-radius: 10%;" src="/poster_images'+val["picture_path"]+'"><span style="display:inline-block;margin-left:7%;">'+area_text+'</span></a></li>';

        })
        $("#picture_tab").html(picture_tab_str);
        var param_obj = {
            picture_department_id:first_picture_department_id,
            picture_path:first_picture_path,
            contents:first_contents,
            contents_confirm: first_contents_confirm,
            user_name: first_user_name,
            deputy_director_name:first_deputy_director_name,
            chief_inspector_name:first_chief_inspector_name

        }

        get_poster_button(_poster_id , page ,param_obj , boolIndex , department_id , mergeImgForm)


    })
}


//点击第几次校稿按钮
$("#poster_num_tab").on("click","a",function(){

    if($(this).parent("li").attr("class") != "active"){
        var poster_contents_id = $(this).attr("poster-contents-id");
        get_page_number(poster_contents_id,true);
    }
})






// 选择页数change事件
$('[name="mod_poster_picture_page"]').chosen().change(function(e){
    var page =  $(this).val();
    var poster_contents_id =  $("#poster_num_tab li.active a").attr("poster-contents-id");
    get_department_id(poster_contents_id,page);




});

// 选择部门change事件
$('[name="mod_poster_picture_department"]').chosen().change(function(e){
    var poster_contents_id =  $("#poster_num_tab li.active a").attr("poster-contents-id");
    var page =  $('[name="mod_poster_picture_page"]').val();
    var department_id =  $(this).val();
    get_picture_list(poster_contents_id,page,department_id , true , department_id);

});



//导出按钮CSV
$(".export-csv-btn").on("click" , function(){
    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_button_csv","poster_contents_id":csv_poster_id,page:csv_page,department_id:csv_department_id},access_token:"<?php echo $access_token?>"};
    ajax_request(param,function(result){
        console.log("/poster_csv" + JSON.parse(result).rtval.url , "成功导出");

        //let src = JSON.parse(result).rtval

        if (JSON.parse(result).rtval){
            var filename = JSON.parse(result).rtval.file_name + '.csv';
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href ="/poster_csv" + JSON.parse(result).rtval.url;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
        }else{
            swal("导出失败" , "当前页面暂无按钮"  , "error");
        }


    })
})


// 图片切换按钮
$("#picture_tab").on("click","a",function(){

    return
    var picture_key = $(this).attr("picture-key");
    /*
    var picture_department_id  = PICTURE_LIST_DATA[picture_key]["picture_department_id"];
    var contents  = PICTURE_LIST_DATA[picture_key]["contents"];
    var contents_confirm  = PICTURE_LIST_DATA[picture_key]["contents_confirm"];
    var picture_path = $(this).attr("picture-path");
    var user_name = PICTURE_LIST_DATA[picture_key]["user_name"];
    */
    var param_obj = {
        picture_department_id:PICTURE_LIST_DATA[picture_key]["picture_department_id"],
        picture_path:$(this).attr("picture-path"),
        contents:PICTURE_LIST_DATA[picture_key]["contents"],
        contents_confirm: PICTURE_LIST_DATA[picture_key]["contents_confirm"],
        user_name: PICTURE_LIST_DATA[picture_key]["user_name"],
        deputy_director_name:PICTURE_LIST_DATA[picture_key]["deputy_director_name"],
        chief_inspector_name:PICTURE_LIST_DATA[picture_key]["chief_inspector_name"]

    };
    change_picture_path(param_obj , true);
})

// 点击切换图片
var change_picture_path = function(param_obj , bool , mergeImgForm){
    // 图片部门ID、图片路径、内容、内容确认、校稿人员、副总监、总监
    var  picture_department_id = param_obj["picture_department_id"];
    var  picture_path = param_obj["picture_path"];
    var  contents = param_obj["contents"] ? param_obj["contents"]:false;
    var  contents_confirm = param_obj["contents_confirm"];

    var  user_name = param_obj["user_name"] == "" ? param_obj["user_name"]:(param_obj["user_name"] == "-2" ? "超过规定校稿时间，系统自动提交":param_obj["user_name"]);
    var  deputy_director_name = param_obj["deputy_director_name"] == "-1" ? "":(param_obj["deputy_director_name"] == "-2" ? "超过规定校稿时间，系统自动提交":param_obj["deputy_director_name"]);
    var  chief_inspector_name = param_obj["chief_inspector_name"] == "-1" ? "":(param_obj["chief_inspector_name"] == "-2" ? "超过规定校稿时间，系统自动提交":param_obj["chief_inspector_name"]);

    // 往tables中添加数据
    $("[name='mod_poster_picture_user_name']").text(user_name);
    $("[name='mod_poster_picture_deputy_director_name']").text(deputy_director_name);
    $("[name='mod_poster_picture_chief_inspector_name']").text(chief_inspector_name);
    $("#poster_contents_table tbody").empty();
    if(contents){
        var historyTemp = JSON.parse(contents);


        var poster_contents_table_str = "";
        for (var k in historyTemp) {
            var text_obj = historyTemp[k];
            var text = text_obj["text"];
            var top = text_obj["top"];
            var left = text_obj["left"];
            // 序号
            var sort_number  = parseInt(k)+1;


            // 判断该内容项是否
            var contents_confirm_str = "";
       if (text_obj["is_confirm"]) {
           //contents_confirm_str = '<span style="cursor:pointer;margin-right:10px;"> <i class="fa fa-check"></i>已确认 </span><span class="label label-info locking-btn" style="cursor:pointer;" onclick="do_contents_locking('+picture_department_id+','+sort_number+');"> 确认修改 </span>'
           contents_confirm_str = '<span class="label label-info locking-btn" style="cursor:pointer;" onclick="do_contents_locking('+picture_department_id+','+sort_number+');"> 确认修改 </span>'

            }else{
           //contents_confirm_str = '<span class="label label-info" style="cursor:pointer;margin-right:10px;" onclick="do_contents_confirm('+picture_department_id+','+sort_number+');"> 确认 </span><span class="label label-info locking-btn" style="cursor:pointer;" onclick="do_contents_locking('+picture_department_id+','+sort_number+');"> 确认修改 </span>'
           contents_confirm_str = '<span class="label label-info locking-btn" style="cursor:pointer;" onclick="do_contents_locking('+picture_department_id+','+sort_number+');"> 确认修改 </span>'

          }
         if(JSON.stringify(text_obj.info) == JSON.stringify(dataInfo)){
             poster_contents_table_str+= '<tr canvas_top="'+top+'" canvas_left="'+left+'" style="background:#f4f4f4;"><td class="text-center">'+sort_number+'</td><td>'+text+'</td> <td>'+bottomList(sort_number , text_obj.info)+'</td> <td class="merge-btn" style="vertical-align: middle;">'+contents_confirm_str+'</td></tr>'
         }else {
             poster_contents_table_str+= '<tr canvas_top="'+top+'" canvas_left="'+left+'" style="background: #cccccc;"><td class="text-center">'+sort_number+'</td><td>'+text+'</td> <td>'+bottomList(sort_number , text_obj.info)+'</td> <td class="merge-btn" style="vertical-align: middle;">'+contents_confirm_str+'</td></tr>'
         }

        }
        $("#poster_contents_table tbody").html(poster_contents_table_str);
    }
    picture_path = "/poster_images"+picture_path;
    // 调用iframe，改变picture和内容
    //$("#iframe_content")[0].contentWindow.initHistory("init_picture_department",picture_path,contents);

    // ========================= 载入图片 并且添加文字标注 ========================

    canvas.clear();


    fabric.Image.fromURL(picture_path, function(oImg) {
        oImg.scale(1); //图片1倍显示
        oImg.lockRotation=true;
        canvas.add(oImg);
        oImg.set('selectable',false);



        //	更新表格数据 ，防止图片变化
        if(!bool){

            // 载入后给桌布缩小显示
            let zoom = 0.5;
            zoom = Math.max(0.2, zoom); //最小为原来的1/10
            zoom = Math.min(1.5, zoom); //最大是原来的3倍
            let delta = new fabric.Point(0-canvas.width/2, 0-canvas.height/2);
            canvas.relativePan(delta);
            let zoomPoint = new fabric.Point(canvas.width/2, canvas.height/2);
            canvas.zoomToPoint(zoomPoint, zoom);

        }

        // 给图片灰度滤镜
        let filter = new fabric.Image.filters.Contrast({
            contrast: -0.3
        });

        // 添加滤镜
        oImg.filters.push(filter);
        // 图片加载完成之后，应用滤镜效果
        oImg.applyFilters();
        //请求重新渲染
        canvas.requestRenderAll();

        set_texts(historyTemp);

        if(mergeImgForm == "0"){
            $(".merge-btn>span").css("display" , "none");
            $(".storage-btn").css("display" , "none");
            $(".operation").css("display" , "none");
        }else{
            $(".merge-btn>span").css("display" , "inline-block").css("padding" , "5px 6px");
            $(".storage-btn").css("display" , "block");
            $(".operation").css("display" , "block");
        }



    });

    // ========================================================================

    // 点击文字跳转到文字位置
    //$("#poster_contents_table tbody tr").on("click",function(){
    //	set_center($(this).attr("canvas_left"),$(this).attr("canvas_top"))
    //})

}




function getMyDate(str) {
    var oDate = new Date(str),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth()+1,
        oDay = oDate.getDate(),
        oHour = oDate.getHours(),
        oMin = oDate.getMinutes(),
        oSen = oDate.getSeconds(),
        oTime = oYear +'-'+ addZero(oMonth) +'-'+ addZero(oDay) +' '+ addZero(oHour) +':'+
            addZero(oMin) +':'+addZero(oSen);
    return oTime;
}

//补零操作
function addZero(num){
    if(parseInt(num) < 10){
        num = '0'+num;
    }
    return num;
}


// 确认修改内容
function do_contents_confirm(picture_department_id,sort_number){

    let data = get_texts();

    data[sort_number-1].is_confirm = true;

    textObj.contents = JSON.stringify(data);

    change_picture_path(textObj , true);

    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"set_contents_confirm","picture_department_id":picture_department_id,contents:JSON.stringify(data)},access_token:"<?php echo $access_token?>"};


    ajax_request(param,function(result){
        var result = JSON.parse(result);
        result = result["rtval"];
        $("#poster_contents_table tbody tr:eq("+(parseInt(sort_number)-1)+") td:eq(3)").html('<span style="cursor:pointer;margin-right:10px;"> <i class="fa fa-check"></i>已确认 </span><span class="label label-info locking-btn" style="cursor:pointer;" onclick="do_contents_locking('+picture_department_id+','+sort_number+');"> 确认修改 </span>');
        //$("#poster_contents_table tbody tr:eq("+(parseInt(sort_number)-1)+") td:eq(3)").html('<span style="cursor:pointer;margin-right:10px;"> <i class="fa fa-check"></i>已确认 </span><span style="cursor: pointer;color:red;" onclick="do_contents_delete('+picture_department_id+','+sort_number+')">删除</span>');
        let data = JSON.parse(textObj.contents_confirm);
        textObj.contents_confirm = JSON.stringify(data);

        if(result != "done"){
            swal("确认完成",result,"success");
        }

    })

}

//删除内容
function do_contents_delete(picture_department_id,index){
    let data =  get_texts()
    data.splice(index-1 , 1)

    textObj.contents =  JSON.stringify(data);

    change_picture_path(textObj , true);

}

//确认修改
function do_contents_locking(picture_department_id,index){
    let data = get_texts();
    data[index-1].locking[identity] = !data[index-1].locking[identity];

    console.log(data[index-1].locking[identity])

    textObj.contents = JSON.stringify(data);
    change_picture_path(textObj , true);
}




//var addAttr = [];
////添加按钮（标注）
//document.getElementsByClassName("add-btn")[0].onclick = _=>{
//    add_text(" 标注 ",true);
//    textObj.contents =  JSON.stringify(get_texts());
//    change_picture_path(textObj , true);
//}

document.getElementsByClassName("all-btn-update")[0].onclick = _=>{
    let data = get_texts();

    for (let index = 0; index < data.length; index++){
        data[index].locking[identity] = true;
    }



    textObj.contents = JSON.stringify(data);
    change_picture_path(textObj , true);

}

//保存按鈕（提交数据）
document.getElementsByClassName("storage-btn")[0].onclick = _=>{
    let lockingBool = true;
    get_texts().map(item=>{
       if(!item.locking[identity]){
           lockingBool = item.locking[identity]
          }
    });

    if (!lockingBool){
        swal("保存失败" , "需要操作全部“确认修改”来表示，已完成工作"  , "error");
        return
    }

    textObj.contents =  JSON.stringify(get_texts());
    let btnList = [];
    JSON.parse(textObj.contents).map((item , index)=>{
        btnList.push(`${index+1}`)
    })

    change_picture_path(textObj , true);


    var param = {url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"set_poster_contents","param":{picture_department_id:picture_department_id ,poster_contents_id:proofread_id,submission:3,contents:textObj.contents},access_token:"<?php echo $access_token?>"}};

    let textArr = JSON.parse(textObj.contents).map(item=>{return item.text;} );
    let newTextArr = [];
    let newTextArr2 = [];

    if(textArr.length <= 0){
        swal("保存失败","相关部门没有导入按钮 ，请导入按钮··· ","error");
        return
    }

    textArr.map(item=>{
        if (newTextArr.indexOf(item) === -1){
        newTextArr.push(item)
    }else {
        newTextArr2.push(item)
    }
    });



    if (newTextArr2.length > 0){
        swal("保存失败","标记文本有重复 ， 请修改···","error");
        return
    }



    ajax_request(param,function(result){
        var result = JSON.parse(result);
        if(result["errcode"] == 0){
            swal("提交成功","","success");
        }else{
            swal("提交失败",result["errmsg"],"error");
        }
    })



}

//按鈕（隐藏 / 显示）
//function onUseBtn(picture_department_id , index){
//    let data =  get_texts();
//    data[index-1].visible = !data[index-1].visible
//
//    textObj.contents =  JSON.stringify(data);
//
//    change_picture_path(textObj , true);
//
//}



//创建查看按钮属性
function bottomList(index , data){

    if(JSON.stringify(data) == JSON.stringify(dataInfo)){
        return `
                    <div class="btn-group">
                                <button data-toggle="dropdown" class="btn btn-default btn-xs dropdown-toggle" >标注信息</button>
                                 <ul class="dropdown-menu" style="width: 250px;left: -200%;padding:0 10px;z-index: 99999;">
                                    ${createTagging(index)}
                                </ul>
                    </div>
     `;
    }else {
        return `
                    <div class="btn-group">
                                <button data-toggle="dropdown" class="btn btn-default btn-xs dropdown-toggle">查看<span class="caret" style="margin-left:3px;"></span>
                                </button>
                                <ul class="dropdown-menu" style="width: 300px;left: -200%;padding:0 10px;z-index: 99999;">
                                    ${createElAttr(index) }
                                </ul>
                            </div>
     `;
    }


}



//保存修改属性
function onUpdateAttr(){
    event.stopPropagation();

    let data = JSON.parse(textObj.contents);
    data.forEach((item , index)=>{
         item.info.attribute = $(`input[name='attribute${index+1}']`)[0].value,
         item.info.desc = $(`input[name='desc${index+1}']`)[0].value,
         item.info.limited_style = $(`input[name='limited_style${index+1}']`)[0].value,
         item.info.name= $(`input[name='name${index+1}']`)[0].value,
         item.info.national_flag = $(`input[name='national_flag${index+1}']`)[0].value,
         item.info.number = $(`input[name='number${index+1}']`)[0].value,
         item.info.original_price = $(`input[name='original_price${index+1}']`)[0].value,
         item.info.page = $(`input[name='page${index+1}']`)[0].value,
         item.info.price = $(`input[name='price${index+1}']`)[0].value,
         item.info.price_bid = $(`input[name='price_bid${index+1}']`)[0].value,
         item.info.producing_area = $(`input[name='producing_area${index+1}']`)[0].value,
         item.info.sku = $(`input[name='sku${index+1}']`)[0].value,
         item.info.time_or_area = $(`input[name='time_or_area${index+1}']`)[0].value,
         item.info.unit = $(`input[name='unit${index+1}']`)[0].value
    })

    textObj.contents = JSON.stringify(data);

}



//创建按钮属性列表
function createElAttr(index){

    let str = ""

    let data = JSON.parse(textObj.contents);
    let text = {
        "sku": "sku",
        "unit": "unit",
        "price": "price",
        "name": "name",
        "desc": "desc",
        "page": "page",
        "idx": "idx",
        "s_price": "s_price",
        "limit": "limit",
        "area_time": "area_time",
        "mark": "mark",
        "origin": "origin",
        "flag": "flag",
        "department_name": "department_name"
    }


        for(key in data[index-1].info){
            str += `
                <li class="flex" style="margin:10px 0;justify-content: space-around;">
<!--                 <div style="width:20%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="${text[key]}">${text[key]}</div>:<input type="text" disabled name="${key}${index}" value="${data[index-1].info[key]}" style="height: 25px;width: 70%;" class="form-control input-sm attr-val">-->
                 <div style="width:20%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="${text[key]}">${text[key]}</div>:<textarea id="ccomment" name="comment" class="form-control" style="height: 30px;" required="" aria-required="true" disabled> ${data[index-1].info[key]}</textarea>

                </li>

            `
        }

    //str += `
    //<li class="divider"></li>
    //<li class="flex" style="margin:10px 0;"> <span class="label label-info" style="cursor:pointer;padding:5px 10px;" onclick="onUpdateAttr(${index})"> 确认修改 </span></li>
    //`;


     return str;
}

//创建按钮标注信息展示框
function createTagging(index) {
    let strTagging = "";
    let data = JSON.parse(textObj.contents);
        if (JSON.stringify(data[index-1].info) == JSON.stringify(dataInfo)) {
            strTagging += `
                <li class="flex" style="margin:10px 0;justify-content: space-around;">

                  <textarea id="ccomment" name="comment" class="form-control" style="height: 200px;" required="" aria-required="true" disabled> ${data[index - 1].tagging}</textarea>

                </li>
            `;
    }
    return strTagging;
}















